<?php

require_once BASEPATH . 'models/authuser.php';

/**
 * Description of WebController
 *
 * @author user
 */
class ChatserverController extends Controller {

    public $auth_user;

    public function __construct() {
        parent::__construct();
    }

    public function _before() {
        parent::_before();

        $this->auth_user = new Authuser();
        $this->view = View::factory("chat/exchange");
    }

    public function index() {
        $exchange = array();

        //Parse JSON data
        $request = json_decode($_POST['data']);

        //ORMs
        $user = new ORM('user');
        $chat_user = new ORM('chat_user');

        //Chat user init : Update my last_conn info
        $chat_user->where("`user_id` = " . $this->auth_user->user->id)->find();
        $last_conn = $chat_user->last_conn;
        $chat_user->last_conn = date("Y-m-d H:i:s", time());
        $chat_user->save();

        ////Process request
        //send msg
        if(isset ($request->send_msg)) {
            $sendmsgs = $request->send_msg;
            foreach ($sendmsgs as $msg) {
                $chat_msg = new ORM('chat_msg');
                $chat_msg->to_id    = $msg->to_id;
                $chat_msg->from_id  = $this->auth_user->user->id;
                $chat_msg->content  = $msg->content;
                $chat_msg->timestamp= date("Y-m-d H:i:s", time());
                $chat_msg->save();
            }
        }

        
        ///Return info
        $um = isset($request->justLogged) ? " " : (" AND `last_update` > '$last_conn' ");
        //Get followee
        $chat_users = $chat_user->query("
            SELECT `chat_user`.* FROM `followings` RIGHT JOIN `chat_user` on (`chat_user`.user_id = `followings`.followee)
            WHERE `followings`.follower = " . $this->auth_user->user->id . $um . "
            GROUP BY `chat_user`.user_id"
        );

        $chat_user_arr = array();
        foreach ($chat_users as $val) {
            $user->find($val->user_id);
            $val->username = $user->username;
            $chat_user_arr[] = $val->getData();
        }
        $exchange['followees'] = $chat_user_arr;

        //Get follower
        $chat_users = $chat_user->query("
            SELECT `chat_user`.* FROM `followings` RIGHT JOIN `chat_user` on (`chat_user`.user_id = `followings`.follower)
            WHERE `followings`.followee = " . $this->auth_user->user->id . $um .
            "GROUP BY `chat_user`.user_id"
        );

        $chat_user_arr = array();
        foreach ($chat_users as $val) {
            $user->find($val->user_id);
            $val->username = $user->username;
            $chat_user_arr[] = $val->getData();
        }
        $exchange['followers'] = $chat_user_arr;

        //Get messages
        $chat_msg = new ORM('chat_msg');
        $query = "(`to_id` = " . $this->auth_user->user->id . " OR `from_id` = " . $this->auth_user->user->id . ") AND `timestamp` > '$last_conn'";
        //echo $query;
        $new_msgs = $chat_msg->where($query)->find_all();
        $new_msgs_arr = array();
        foreach($new_msgs as $new_msg) {
            $new_msgs_arr[] = $new_msg->getData();
        }
        $exchange['new_msgs'] = $new_msgs_arr;

        //Clean up messages - when is the best time ?
        $msg_expire = 60;
        DBQuery::instance()->query("
            delete from chat_msg where timestampdiff(MINUTE, timestamp, now()) > $msg_expire
        ");

        //Checking for user... set offline if timeout
        $timeout = 2;
        DBQuery::instance()->query("
           update chat_user set is_online = 0 where timestampdiff(MINUTE, last_conn, now()) > $timeout
        ");

        //Send it to exchange buffer
        $this->view->exchange_data = json_encode($exchange);
    }

    public function userupdate() {
        //Parse JSON data
        $request = json_decode($_POST['data']);
        
        //Get chat user and update the data
        $chat_user = new ORM('chat_user');
        $chat_user->where("`user_id` = " . $this->auth_user->user->id)->find();
        $chat_user->is_online   = "$request->is_online";
        $chat_user->status      = $request->status;
        $chat_user->last_update = date("Y-m-d H:i:s", time());
        $chat_user->save();

        $user = new ORM('user');
        $user->find($chat_user->user_id);
        $chat_user->username = $user->username;

        //Send it to exchange buffer
        $this->view->exchange_data = $chat_user->toJsonString();
    }

}

?>
